/**
 * 音效管理器
 * Name = audioManager
 * DateTime = Sat Jan 15 2022 20:38:39 GMT+0800 (中国标准时间)
 * Author = Created by zhj9922
 * FileBasename = audioManager.ts
 * gitee： https://gitee.com/coyeking
 */
 
import { sys,resources,AudioClip,log,AudioSource,clamp01} from 'cc';
 
export class audioManager {
	static _instance: audioManager;
	
    static get instance () {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new audioManager();
		this._instance.init();
        return this._instance;
    }
    private musicVolume: number = 1;
    private soundVolume: number = 1;
    private _bgaudioSource : AudioSource = new AudioSource();

    private init () {
        if (!sys.localStorage.getItem('MusicVolume')) {
            sys.localStorage.setItem('MusicVolume', this.musicVolume.toString());
            sys.localStorage.setItem('SoundVolume', this.soundVolume.toString());
        } else {
            this.musicVolume = parseFloat(sys.localStorage.getItem('MusicVolume'));
            this.soundVolume = parseFloat(sys.localStorage.getItem('SoundVolume'));
        }
	};
    
    /**
     * 获取AudioClip
     * @param url 
     * @param callback 
     * @returns 
     */
    private getUrl(url:string,callback){
        return resources.load("sounds/" + url ,AudioClip, (err: any, clip: AudioClip)=>{
            if (err){
                log('音效加载失败');
                return;
            }
            callback(clip);
         })
    };

    /**
     * 
     * @param url 音效地址
     * @param volumeScale 播放音量倍数
     */
    public playSound(url:string = 'click',volumeScale: number = 1){
        var self = this;
        var callback = function(assets){
            if(self.soundVolume > 0){
                let clip = assets as AudioClip;
                let audioSource = new AudioSource();
                audioSource.volume = self.soundVolume;
                audioSource.playOneShot(clip, volumeScale);
            }
        }
        self.getUrl(url,callback);
    };

    /**
     * 播放背景音乐
     * @param url 音效地址
     */
    public playMusic (url:string){
        var self = this;
        const audioSource = self._bgaudioSource!;
        if (audioSource.playing){
            self._bgaudioSource.stop();
        }
        var callback = function(assets){
            if(self.musicVolume > 0){
                let clip = assets as AudioClip;
                self._bgaudioSource = new AudioSource();
                self._bgaudioSource.clip = clip;
                self._bgaudioSource.loop = true;
                self._bgaudioSource.volume = self.musicVolume;
                self._bgaudioSource.play();
            }
        }
        self.getUrl(url,callback);
    }
	
}

